<?php


namespace app\api\controller\v1;


use app\api\controller\v1\Clue as ClueModel;
use app\common\model\ClueErrorLog;
use app\lib\exception\ParamException;
use fast\Http;
use other\Rsa;
use think\Db;

/**
 * 北京华资
 */
class BeiJingHuaZi
{

    public function pushClue($mapping, $clue_info, $listPush)
    {

        $apiName = '【' . $mapping['api_name'] . '】';

//        $clue_info['clue_name']='测试张';
//        $clue_info['phone']='13000000004';

        $this->getValidate($apiName,$clue_info); // 手机号码的撞库

        $clue_rule = json_decode($mapping['rule_json'], true);
        $params = [];
        if (!$clue_rule) {
            $errMsg = $apiName . '读取商户接收规则失败';
            ClueErrorLog::record($clue_info['clue_id'], $errMsg, $clue_info);
            model('Clue')->where('id', $clue_info['id'])->update(['err_msg' => $errMsg]);
            throw new ParamException(['msg'=>$errMsg,'errorCode'=>10001]);
        } else {

            foreach ($clue_rule as $v) {
                $params[$v['curr']] = $clue_info[$v['orig']];
                if ($v['orig'] == 'city') {
                    $citys = explode('-', $clue_info[$v['orig']]);
                    $city_info = Db::name('city')->where(['type' => 2, 'id' => $citys[1]])->find();
                    $params[$v['curr']] = $city_info['name'];
                }
            }

            $params['money']=$clue_info['apply_limit'];

            if (!empty($clue_info['show_city'])) {
                if (strpos($clue_info['show_city'], '-') !== false) {
                    $city_t = explode('-', $clue_info['show_city']);
                    if (count($city_t) == 3) {
                        $params['city'] = $city_t[1];
                    } elseif (count($city_t) == 2) {
                        $params['city'] = $city_t[1];
                    } elseif (count($city_t) == 1) {
                        $params['city'] = $city_t[0];
                    }
                }else{
                    $params['city']=$clue_info['show_city'];
                }
            }

            $params['remark'][]=get_product_desc($clue_info['pro_id']);


            $postData['param'] = $params;

            $api_url = $mapping['api_url'];


//            dump($params);
//            die;
            $res_json = $this->postJson($api_url, $params);
//            $res_json = preg_replace('/[\x{FEFF}-\x{FFFF}]/u', '', $res_json);
            $res = json_decode($res_json, true);
//            dump($res);die;
            if (!empty($res)) {
                $res['params'] = $postData;
                if ($res['code'] != 200) {
                    $errMsg = $apiName . '线索推送商户处理失败：' . $res['message'];
                    ClueErrorLog::record($clue_info['clue_id'], $errMsg, $res);
                    model('Clue')->where('id', $clue_info['id'])->update(['err_msg' => $errMsg]);
                    throw new ParamException(['msg' => $errMsg, 'errorCode' => 10001]);
                }
            } else {
                $errMsg = $apiName . '线索推送商户请求失败';
                ClueErrorLog::record($clue_info['clue_id'], $errMsg, $postData);
                model('Clue')->where('id', $clue_info['id'])->update(['err_msg' => $errMsg]);
                throw new ParamException(['msg' => $errMsg, 'errorCode' => 10001]);
            }
            return $res;
        }
    }

//可以直接用
    public function getValidate($apiName,$clue_info)
    {
        $phone=$clue_info['phone'];
        $api_url = 'https://api.hzyidai.cn/Collide_phone/all_collide_phone.html';

        $api_params = [
            'md5mobile'=>strtolower(md5($phone)),
        ];


        $res_json = $this->postJson($api_url, $api_params);
        $res  = json_decode($res_json, true);
//        dump($res);die;

        if(!empty($res)){
            if($res['code']!=12){
                $errMsg=$apiName.'CRM手机号码的撞库失败：'.$res['msg'];
                ClueErrorLog::record($clue_info['clue_id'],$errMsg,$res);
                model('Clue')->where('id',$clue_info['id'])->update(['err_msg'=>$errMsg]);
                throw new ParamException(['msg'=>$errMsg,'errorCode'=>10001]);
            }else{
//                if($res['data']['phoneMd5Exist']){
//                    if(empty($clue_info['is_find'])&&!empty($clue_info['clue_city']) && $clue_info['clue_city'] != $clue_info['city']){
//                        $clue_info['city'] = $clue_info['clue_city'];
//                        $clue_info['next_city'] = $clue_info['clue_city'];
//                        $listPush[]=$clue_info['push_id'];
//                        $clueRes=(new ClueModel())->cluePush($clue_info, false, $listPush);
//                        if($clueRes['code']!=200){
//                            $errMsg=$clueRes['msg'];
//                            ClueErrorLog::record($clue_info['clue_id'],$errMsg,$res);
//                            model('Clue')->where('id',$clue_info['id'])->update(['err_msg'=>$errMsg]);
//                            throw new ParamException(['msg'=>$errMsg,'errorCode'=>10001]);
//                        }
//                    }else{
//                        $errMsg=$apiName.'CRM手机号码的撞库重复';
//                        ClueErrorLog::record($clue_info['clue_id'],$errMsg,$res);
//                        model('Clue')->where('id',$clue_info['id'])->update(['err_msg'=>$errMsg]);
//                        $isRe=Db::name('clue_err_log')->where(['type'=>2,'adv_id'=>$clue_info['adv_id'],'pro_id'=>$clue_info['pro_id'],'clue_id'=>$clue_info['id']])->find();
//                        if(empty($isRe)){
//                            Db::name('clue_err_log')->insert([
//                                'type'=>2,
//                                'clue_id'=>$clue_info['id'],
//                                'adv_id'=>$clue_info['adv_id'],
//                                'pro_id'=>$clue_info['pro_id'],
//                                'city'=>$clue_info['city'],
//                                'create_time'=>time()]);
//                        }
//                        if(empty($clue_info['is_find'])){
//                            $listPush[]=$clue_info['push_id'];
//                            $clueRes=(new ClueModel())->cluePush($clue_info, false, $listPush);
//                            if($clueRes['code']!=200){
//                                $errMsg=$clueRes['msg'];
//                                ClueErrorLog::record($clue_info['clue_id'],$errMsg,$res);
//                                model('Clue')->where('id',$clue_info['id'])->update(['err_msg'=>$errMsg]);
//                                throw new ParamException(['msg'=>$errMsg,'errorCode'=>10001]);
//                            }
//                        }else{
//                            throw new ParamException(['msg'=>$errMsg,'errorCode'=>10001]);
//                        }
//                    }
//                }
            }
        }else{
            $errMsg=$apiName.'CRM手机号码的撞库请求失败';
            ClueErrorLog::record($clue_info['clue_id'],$errMsg,$clue_info);
            model('Clue')->where('id',$clue_info['id'])->update(['err_msg'=>$errMsg]);
            throw new ParamException(['msg'=>$errMsg,'errorCode'=>10001]);
        }
        return $res;
    }

    /**
     * post发送json格式的数据
     */
    public function postJson($url, $data)
    {
        $curl = curl_init();

        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_TIMEOUT, 10);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        if (!$data) {
            throw new ParamException(['msg' => '请求数据不能为空', 'errorCode' => 10000]);
        }
        $params = json_encode($data, JSON_UNESCAPED_UNICODE);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $params);
        curl_setopt($curl, CURLOPT_HEADER, 0);
//        curl_setopt($curl, CURLOPT_HTTPHEADER, array(
//            'Content-Type: application/json; charset=utf-8',
//        ));
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $res = curl_exec($curl);
        curl_close($curl);
        //writelog("请求日志".$params. "====". $res. "====". $url);
        return $res;
    }



}